﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XingLucifer.IBase;
using XingLucifer.IBase.Enums;

namespace XingLucifer.Devices.Devices.ScanCode
{
    public class Keenes_SR : IDevices
    {
        private ICommunication _com;
        private byte[] _start = Encoding.ASCII.GetBytes("LON\r\n");
        private byte[] _end = Encoding.ASCII.GetBytes("LOFF\r\n");
        private CancellationTokenSource _token;
        public Keenes_SR(ICommunication com, CancellationTokenSource token)
        {
            _com = com;
            _token = token;
        }

        public void Close() => _com.Close();

        public bool Open() => _com.Open();

        public Task Read()
        {
            throw new NotImplementedException("未实现");
        }

        public TClass ReadClass<TClass>(int address, TClass obj = null, int count = 3) where TClass : class
        {
            throw new NotImplementedException("未实现");
        }

        public TValue ReadSingle<TValue>(int address, int length, int count = 1)
        {
            for (int i = 0; i < count; i++)
            {
                try
                {
                    var timout = _com.Timeout;
                    _com.Timeout = 50;
                    _com.Read(length);
                    _com.Timeout = timout;

                    var bytes = _com.Write(_start);
                    if (bytes)
                    {
                        byte[] barcode_bytes = _com.Read(length);
                        string barcode = Encoding.ASCII.GetString(barcode_bytes).TrimEnd();
                        _com.Write(_end);
                        return (TValue)(object)barcode;
                    }
                    return default;
                }
                catch (Exception)
                {
                    if (_token.Token.IsCancellationRequested)
                    {
                        return default;
                    }
                    Thread.Sleep(100);
                    _com.ReconnectDisconnection?.Invoke(_com, _com.Index, _com.IP, _com.Port, _com.DeviceType, _com.TaskType, _com.ServiceName, _token);
                }
            }
            return default;
        }

        public bool WriteClass<TClass>(TClass value, int address, int count = 3) where TClass : class
        {
            throw new NotImplementedException("未实现");
        }

        public bool WriteSingle(object value, int address, int offset, int length, int count = 3)
        {
            throw new NotImplementedException("未实现");
        }
    }
}
